import React, { useState, useEffect, useRef } from "react"
import "./home.css"
import { getTasks } from "../../services/upload"

export default function Home() {

    //存放三个位置的任务
    const [prepare, setPrepare] = useState([]);
    const [learning, setLearning] = useState([]);
    const [complete, setComplete] = useState([]);
    const [btnEnable, setBtnEnable] = useState(false); //用来判断是否当前正在添加
    const [username, setUsername] = useState("");
    const [greet, setGreet] = useState("");
    const btn = useRef(null);

    const greets = ["Good Morning", "Good Noon", "Good Afternoon", "Good Evening"];
    const addTask = () => {//点击添加任务
        if (btnEnable === true) //不可用
        {
            alert("请完成当前添加");
        }
        else { //当点击了一次新增的时候，添加按钮变成不可用，即完成一个任务的添加之前，不能再同时添加另一个任务
            setBtnEnable(true)
            let btnElem = btn.current; //获得按钮节点
            //需要新增一个输入框
            let newInput = document.createElement("input");
            newInput.style.outline = "none";
            newInput.style.border = "none";
            newInput.style.margin = "10px";
            newInput.style.height = "20px";
            btnElem.insertAdjacentElement("beforebegin", newInput);
            const ok = () => {
                setBtnEnable(false);
                newInput.remove()
                //失去焦点的时候判断输入的内容是否为空，如果是空就取消次的添加
                if (!now || !now.replaceAll(' ', '')) {//去除空格，如果是空的，则取消本次添加
                }
                else { //如果完成了输入 ，则将新添加好的事件显示在列表中
                    let res = [...prepare];
                    res.push(now);
                    setPrepare(res);
                }
            }
            //添加输入监听
            let now;
            newInput.addEventListener("change", (event) => {
                now = event.target.value;
            })
            newInput.addEventListener("blur", ok);
        }
    }

    //获取三个板块在当前窗口上的位置
    const getPrepearLocation = () => {
        var temp = document.querySelector("#content_P");
        return {
            left: temp.offsetLeft,
            top: temp.offsetTop,
            right: temp.offsetLeft + 200,
            bottom: temp.offsetTop + 340
        }
    }
    const getLearningLocation = () => {
        var temp = document.querySelector("#content_L");
        return {
            left: temp.offsetLeft,
            top: temp.offsetTop,
            right: temp.offsetLeft + 200,
            bottom: temp.offsetTop + 340
        }
    }
    const getCompleteLocation = () => {
        var temp = document.querySelector("#content_C")
        return {
            left: temp.offsetLeft,
            top: temp.offsetTop,
            right: temp.offsetLeft + 200,
            bottom: temp.offsetTop + 340
        }
    }


    const check = (center) => { //检查位置
        // 获取三个板块的上下左右位置
        const preBoxLocation = getPrepearLocation();
        const leaBoxLocation = getLearningLocation();
        const comBoxLocation = getCompleteLocation();
        const { x, y } = center;
        if (x >= preBoxLocation.left && x <= preBoxLocation.right && y >= preBoxLocation.top && y <= preBoxLocation.bottom) {
            return 'content_P';
        }
        if (x >= leaBoxLocation.left && x <= leaBoxLocation.right && y >= leaBoxLocation.top && y <= leaBoxLocation.bottom) {
            return 'content_L'
        }
        if (x >= comBoxLocation.left && x <= comBoxLocation.right && y >= comBoxLocation.top && y <= comBoxLocation.bottom) {
            return 'content_C'
        }
        return "no";
    }

    const clear = () => {//清除mouseup事件
        document.onmouseup = ""
    }

    const handleDelete = (type, taskName) => {//接收传过来的任务来源——代办、进行中、已完成，以及任务名
        console.log("删除", type, taskName);
        if (type === "content_P") {
            let newP = [...prepare];
            let index = newP.indexOf(taskName);
            newP.splice(index, 1);
            setPrepare(newP);
        }
        if (type === "content_L") {
            let newL = [...learning];
            let index = newL.indexOf(taskName);
            newL.splice(index, 1);
            setLearning(newL);
        }
        if (type === "content_C") {
            let newC = [...complete];
            let index = newC.indexOf(taskName);
            newC.splice(index, 1);
            setComplete(newC);
        }
    }


    const mouseDown = (event) => {//事件代理
        if (event.target.tagName.toLowerCase() === 'span') {//如果是点击删除
            const type = event.target.parentElement.getAttribute("class");//得到当前任务的父亲
            let taskName = event.target.parentElement.innerText.replace("\n", "").replace("+", "")
            handleDelete(type, taskName);
            event.stopPropagation();//停止事件的传播
        } else {
            const moveElem = event.target; //正在移动的对象
            const type = moveElem.parentElement.getAttribute("id");//得到当前任务的父亲
            //1 得到的是当前鼠标按下的时候的坐标位置，以及相对于任务自身的偏移量
            let clickX = event.clientX; //相对于窗口
            let clickY = event.clientY;
            let offX = event.offsetX; //相对于任务盒子自身的偏移量
            let offY = event.offsetY;
            moveElem.style.zIndex = 20;//设置层级，覆盖在其他盒子之上

            //2 鼠标移动过程中修改top、left
            const willArr = ["content_P", "content_L", "content_C"]
            document.onmousemove = (moveEvent) => {//在鼠标的移动过程中,重新计算top和left属性
                moveElem.style.left = moveEvent.clientX - clickX + "px";
                moveElem.style.top = moveEvent.clientY - clickY + "px";
                let centerClient = {
                    x: moveEvent.clientX - offX + 83,
                    y: moveEvent.clientY - offY + 13
                }

                const res = check(centerClient); //如果符合范围，修改显示的样式
                if (res !== "no") {  //互斥修改，一次只可能在一个范围内
                    const will = document.querySelector(`#${res}`);
                    will.style.boxShadow = " 0px 0px 5px 1px rgb(255, 255, 255)";
                } else {
                    willArr.forEach((item) => { document.querySelector(`#${item}`).style.boxShadow = "" })
                }
            }

            //3 鼠标弹起的时候，计算当前移动到了哪里？如果符合板块位置，则作相应的调整
            document.onmouseup = (upEvent) => {//鼠标弹起的时候
                moveElem.style.zIndex = "";//修改显示层级为默认
                document.onmousemove = "";//清除mousemove

                //(1) 计算出任务div的中心点的位置在窗口中的坐标
                let centerClient = {
                    x: upEvent.clientX - offX + 83,//任务盒子宽的一半
                    y: upEvent.clientY - offY + 13//任务盒子高的一半
                }
                //(2) 判断centerClient这个点是落在哪个板块,并且相应的修改state
                const res = check(centerClient);
                if (res !== type && res !== "no") {//跟原本的板块不一样才执行修改
                    let innerTask = moveElem.innerText.replace("\n", "").replace("+", "");
                    if (res === "content_P") {
                        let newP = [...prepare];
                        newP.push(innerTask);
                        setPrepare(newP);

                        if (type === "content_L") {
                            let newL = [...learning];
                            let index = newL.indexOf(innerTask);
                            newL.splice(index, 1);
                            setLearning(newL);
                        } else {
                            let newC = [...complete];
                            let index = newC.indexOf(innerTask);
                            newC.splice(index, 1);
                            setComplete(newC);
                        }

                    }
                    if (res === "content_L") {
                        let newL = [...learning];
                        newL.push(innerTask);
                        setLearning(newL);

                        if (type === "content_P") {
                            let newP = [...prepare];
                            let index = newP.indexOf(innerTask);
                            newP.splice(index, 1);
                            setPrepare(newP);
                        } else {
                            let newC = [...complete];
                            let index = newC.indexOf(innerTask);
                            newC.splice(index, 1);
                            setComplete(newC);
                        }
                    }
                    if (res === "content_C") {
                        let newC = [...complete];
                        newC.push(innerTask);
                        setComplete(newC);
                        if (type === "content_P") {
                            let newP = [...prepare];
                            let index = newP.indexOf(innerTask);
                            newP.splice(index, 1);
                            setPrepare(newP);
                        } else {
                            let newL = [...learning];
                            let index = newL.indexOf(innerTask);
                            newL.splice(index, 1);
                            setLearning(newL);
                        }
                    }
                }
                //不满足板块条件的话，回到最初的位置
                moveElem.style.left = 0;
                moveElem.style.top = 0;
                willArr.forEach((item) => {//将板块的边框变成透明
                    document.querySelector(`#${item}`).style.boxShadow = ""
                })
                clear();//清除鼠标松开事件，
            }
        }
    }

    const getTask = async () => {
        const res = await getTasks();
        console.log(res.data);
        let tasklist = res.data.taskList;
        if (res.code === 200) {//在这里筛分
            // console.log("正确")
            let p = [];
            let l = [];
            let c = [];
            tasklist.forEach((item, index) => {
                if (item.type === "P") {
                    p.push(item.name);
                }
                else if (item.type === "L") {
                    l.push(item.name)
                }
                else {
                    c.push(item.name);
                }
            })
            setPrepare(p);
            setLearning(l);
            setComplete(c);
        }
    }

    useEffect(() => {
        let task = document.querySelectorAll("#task");
        task.forEach((task) => {
            task.addEventListener("mousedown", mouseDown, false);
        })
        return (//return中的函数在组件即将卸载的时候执行，清除副作用，避免多次添加mousedown事件
            function () {
                task.forEach((task) => {
                    task.removeEventListener("mousedown", mouseDown, false);
                })
            }
        )
    }, [prepare, learning, complete])//prepare, learning, complete三个状态任意一个或多个发生改变时触发函数执行


    useEffect(() => {
        getTask();
        const username = JSON.parse(window.sessionStorage.getItem("username")); //获得用户名
        if (username) setUsername(username.username);
        let now = new Date();
        let hour = now.getHours();
        console.log(hour);
        if (hour >= 6 && hour < 12) {
            setGreet(greets[0])
        }
        if (hour >= 12 && hour < 14) {
            setGreet(greets[1])
        }
        if (hour >= 14 && hour < 18) {
            setGreet(greets[2])
        }
        if (hour >= 18 && hour < 24) {
            setGreet(greets[3])
        }
        if (hour >= 0 && hour < 6) {
            setGreet(greets[3])
        }
    }, [])//组件挂载完成后执行一次


    return (
        <div className="Home">
            <div className="name">{greet + "! " + username}</div>
            <div id="d_prepear">
                <div id="tip"> Prepear to study</div>
                <div id="content_P"  >
                    {
                        prepare.map((item, index) => {
                            return (
                                <div id="task" className="content_P" key={index}>
                                    {item}   <span className="cha">+</span>
                                </div>
                            )
                        })
                    }
                    <button id="add" ref={btn} onClick={addTask} >
                        +
                    </button>
                </div>
            </div>
            <div id="d_learning">
                <div id="tip">Learning</div>
                <div id="content_L">
                    {
                        learning.map((item, index) => {
                            return (
                                <div id="task" className="content_L" key={index}>
                                    {item}
                                    <span className="cha">+</span>
                                </div>
                            )
                        })
                    }
                </div>
            </div>
            <div id="d_complete">
                <div id="tip">complete</div>
                <div id="content_C">
                    {
                        complete.map((item, index) => {
                            return (
                                <div id="task" className="content_C" key={index}>
                                    {item}
                                    <span className="cha">+</span>
                                </div>
                            )
                        })
                    }
                </div>

            </div>
        </div>
    )
}